package com.yic.module.device.controller.admin.device;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.yic.framework.common.enums.CommonStatusEnum;
import com.yic.module.base.api.brand.BrandApi;
import com.yic.module.base.api.brand.dto.BrandRespDTO;
import com.yic.module.base.api.center.CenterApi;
import com.yic.module.base.api.center.dto.CenterRespDTO;
import com.yic.module.base.api.factory.FactoryApi;
import com.yic.module.base.api.factory.dto.FactoryRespDTO;
import com.yic.module.base.api.supplier.SupplierApi;
import com.yic.module.base.api.supplier.dto.SupplierRespDTO;
import com.yic.module.base.api.unit.UnitApi;
import com.yic.module.base.api.unit.dto.UnitRespDTO;
import com.yic.module.device.dal.dataobject.deviceCategory.DeviceCategoryDO;
import com.yic.module.device.service.deviceCategory.DeviceCategoryService;
import com.yic.module.system.api.dept.DeptApi;
import com.yic.module.system.api.dept.dto.DeptRespDTO;
import com.yic.module.system.api.user.AdminUserApi;
import com.yic.module.system.api.user.dto.AdminUserRespDTO;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import org.springframework.validation.annotation.Validated;
import org.springframework.security.access.prepost.PreAuthorize;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Operation;

import javax.validation.constraints.*;
import javax.validation.*;
import javax.servlet.http.*;
import java.util.*;
import java.io.IOException;

import com.yic.framework.common.pojo.PageResult;
import com.yic.framework.common.pojo.CommonResult;
import static com.yic.framework.common.pojo.CommonResult.success;

import com.yic.framework.excel.core.util.ExcelUtils;

import com.yic.framework.operatelog.core.annotations.OperateLog;
import static com.yic.framework.operatelog.core.enums.OperateTypeEnum.*;

import com.yic.module.device.controller.admin.device.vo.*;
import com.yic.module.device.dal.dataobject.device.DeviceDO;
import com.yic.module.device.convert.device.DeviceConvert;
import com.yic.module.device.service.device.DeviceService;

@Tag(name = "管理后台 - 设备基本信息")
@RestController
@RequestMapping("/device/device")
@Validated
public class DeviceController {

    @Resource
    private DeviceService deviceService;
    @Resource
    private DeviceCategoryService deviceCategoryService;
    @Resource
    private DeptApi deptApi;
    @Resource
    private AdminUserApi adminUserApi;
    @Resource
    private CenterApi centerApi;
    @Resource
    private BrandApi brandApi;
    @Resource
    private SupplierApi supplierApi;
    @Resource
    private UnitApi unitApi;
    @Resource
    private FactoryApi factoryApi;


    @PostMapping("/create")
    @Operation(summary = "创建设备基本信息")
    @PreAuthorize("@ss.hasPermission('device:device:create')")
    public CommonResult<Long> create(@Valid @RequestBody DeviceCreateReqVO createReqVO) {
        return success(deviceService.create(createReqVO));
    }

    @PutMapping("/update")
    @Operation(summary = "更新设备基本信息")
    @PreAuthorize("@ss.hasPermission('device:device:update')")
    public CommonResult<Boolean> update(@Valid @RequestBody DeviceUpdateReqVO updateReqVO) {
        deviceService.update(updateReqVO);
        return success(true);
    }

    @DeleteMapping("/delete")
    @Operation(summary = "删除设备基本信息")
    @Parameter(name = "id", description = "编号", required = true)
    @PreAuthorize("@ss.hasPermission('device:device:delete')")
    public CommonResult<Boolean> delete(@RequestParam("id") Long id) {
        deviceService.delete(id);
        return success(true);
    }

    @GetMapping("/get")
    @Operation(summary = "获得设备基本信息")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    @PreAuthorize("@ss.hasPermission('device:device:query')")
    public CommonResult<DeviceRespVO> get(@RequestParam("id") Long id) {
        DeviceDO device = deviceService.get(id);
        return success(DeviceConvert.INSTANCE.convert(device));
    }

    @GetMapping("/list")
    @Operation(summary = "获得设备基本信息列表")
    @Parameter(name = "ids", description = "编号列表", required = true, example = "1024,2048")
    @PreAuthorize("@ss.hasPermission('device:device:query')")
    public CommonResult<List<DeviceRespVO>> getList(@RequestParam("ids") Collection<Long> ids) {
        List<DeviceDO> list = deviceService.getList(ids);
        return success(DeviceConvert.INSTANCE.convertList(list));
    }

    @GetMapping("/list-all-simple")
    @Operation(summary = "获取设备精简信息列表", description = "只包含被开启的设备，主要用于前端的下拉选项")
    public CommonResult<List<DeviceSimpleRespVO>> getSimpleDeviceList() {
        // 获得设备列表，只要开启状态的
        List<DeviceDO> list = deviceService.getDeviceList(null, null);
        return success(DeviceConvert.INSTANCE.convertList03(list));
    }

    @GetMapping("/page")
    @Operation(summary = "获得设备基本信息分页")
    @PreAuthorize("@ss.hasPermission('device:device:query')")
    public CommonResult<PageResult<DeviceRespVO>> getPage(@Valid DevicePageReqVO pageVO) {
        PageResult<DeviceDO> pageResult = deviceService.getPage(pageVO);

        PageResult<DeviceRespVO> resp = DeviceConvert.INSTANCE.convertPage(pageResult);
        //组装数据，由于组装数据均在redis中有缓存，可循环取值
        if (CollectionUtil.isNotEmpty(resp.getList())) {
            resp.getList().forEach(item -> {
                // 封装设备分类
                DeviceCategoryDO category = deviceCategoryService.getCategory(item.getId());
                if (ObjectUtil.isNotEmpty(category)) {
                    item.setCategoryName(category.getName());
                }
                // 封装部门
                DeptRespDTO dept = deptApi.getDept(item.getDeptId());
                if (ObjectUtil.isNotEmpty(dept)) {
                    item.setDeptName(dept.getName());
                }
                //封装使用人
                AdminUserRespDTO user = adminUserApi.getUser(item.getUserId());
                if (ObjectUtil.isNotEmpty(user)) {
                    item.setUserName(user.getNickname());
                }
                // 封装管理员
                AdminUserRespDTO admin = adminUserApi.getUser(item.getAdminId());
                if (ObjectUtil.isNotEmpty(admin)) {
                    item.setAdminName(admin.getNickname());
                }
                // 封装品牌
                BrandRespDTO brand = brandApi.getBrand(item.getBrandId());
                if (ObjectUtil.isNotEmpty(brand)) {
                    item.setBrandName(brand.getName());
                }
                // 封装工作中心
                CenterRespDTO center = centerApi.getCenter(item.getCenterId());
                if (ObjectUtil.isNotEmpty(center)) {
                    item.setCenterName(center.getName());
                }
                // 封装供应商
                SupplierRespDTO supplier = supplierApi.getSupplier(item.getSupplierId());
                if (ObjectUtil.isNotEmpty(supplier)) {
                    item.setSupplierName(supplier.getName());
                }
                // 封装单位
                UnitRespDTO unit = unitApi.getUnit(item.getUnitId());
                if (ObjectUtil.isNotEmpty(unit)) {
                    item.setUnitName(unit.getName());
                }
                // 封装工厂
                FactoryRespDTO factory = factoryApi.getFactory(item.getFactoryId());
                if (ObjectUtil.isNotEmpty(factory)) {
                    item.setFactoryName(factory.getName());
                }
            });
        }
        return success(resp);
    }

    @GetMapping("/export-excel")
    @Operation(summary = "导出设备基本信息 Excel")
    @PreAuthorize("@ss.hasPermission('device:device:export')")
    @OperateLog(type = EXPORT)
    public void exportExcel(@Valid DeviceExportReqVO exportReqVO,
              HttpServletResponse response) throws IOException {
        List<DeviceDO> list = deviceService.getList(exportReqVO);
        // 导出 Excel
        List<DeviceExcelVO> datas = DeviceConvert.INSTANCE.convertList02(list);
        ExcelUtils.write(response, "设备基本信息.xls", "数据", DeviceExcelVO.class, datas);
    }

}
